package de.mud.jta.plugin;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

import bsh.EvalError;
import bsh.Interpreter;
import de.mud.jta.FilterPlugin;
import de.mud.jta.Plugin;
import de.mud.jta.PluginBus;
import de.mud.jta.PluginConfig;
import de.mud.jta.Repository;
import de.mud.jta.VisualPlugin;
import de.mud.jta.event.ConfigurationListener;


public class BshUtil extends Plugin implements FilterPlugin, VisualPlugin {
	
	/* ========== Constant ========= */
    // Output folder ( Configuration )
    private String snapfolder;
    
	private static final String NEWLINE = "\n";
	
	private final static int WIDTH = 80;
	private final static int HEIGHT = 24;
	
	private String username;
	
	private String passwd;
	
    // Script Home (Configuration)
    private String defaultFolder;
    
    
    // Visual Menu
    private JMenu menu;

    /* =========Bsh Player========== */
    
    private class Player implements Runnable {
    	
    	private String filename;
    	
    	public Player(String filename) {
    		this.filename = filename;
    	}
    	
		public void run() {
        	Interpreter interpreter = new Interpreter();
        	
        	try {
        		initial(interpreter);
				interpreter.source(filename);
				interpreter.eval("test();");
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (EvalError e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
        	//interpreter.run();
		}}
    /* =========FileterPlugin========= */

    /**
     * Constructor of MFGUtil.
     *
     * @param bus
     * @param id
     */
    public BshUtil(PluginBus bus, final String id) {
        super(bus, id);

        // Get configuation from properties
        bus.registerPluginListener(new ConfigurationListener() {
                public void setConfiguration(PluginConfig config) {
                    snapfolder = config.getProperty("BshUtil", id,
                            "snapshoot_folder");
                    username = config.getProperty("BshUtil", id,
                    		"username");
                    passwd = config.getProperty("BshUtil", id,
                    		"passwd");
                    defaultFolder = config.getProperty("BshUtil", id,
            				"default_folder");
                } // end setConfiguration()
            } // end new
        );

        // Menu Initialization
        menu = new JMenu("BSH Util");

        JMenuItem playfile = new JMenuItem("Play File");
        playfile.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    final JFileChooser fileChooser = new JFileChooser();

                    if (fileChooser.showOpenDialog(Repository.frameMain) == JFileChooser.APPROVE_OPTION) {
                    	Thread newThread = new Thread(new Player(fileChooser.getSelectedFile().getPath()));
                    	newThread.start();
                    } // end if


                } // end actionPerformed()
            } // end new
        );

        menu.add(playfile);

        // TODO Auto-generated constructor stub
    } // end MFGUtil()

    protected void initial(Interpreter interpreter) throws EvalError {
		interpreter.set("src", source);
		interpreter.set("RETURN", "" + (char)13);
		interpreter.set("TAB", "" + (char)9);
		interpreter.set("USER", username);
		interpreter.set("PWD", passwd);
		
	}

	/* =========FileterPlugin========= */
    protected FilterPlugin source;

    public void setFilterSource(FilterPlugin source) {
        System.out.println(source);
        this.source = source;
    } // end setFilterSource()

    public FilterPlugin getFilterSource() {
        return source;
    } // end getFilterSource()

    public int read(byte[] b) throws IOException {
        // printBytes(b);
        return source.read(b);
    } // end read()

    public void write(byte[] b) throws IOException {
        source.write(b);
        
    } // end write()


    private static void printScreen(FileWriter fw, char[][] charArray) {
        int start = charArray.length - HEIGHT;

        for (int i = start; i < charArray.length; i++) {
            String s = "";

            for (int j = 0; j < WIDTH; j++) {
                s = s + charArray[i][j];
            } // end for

            writeString(fw, s);

            // System.out.println(s);
        } // end for
    } // end printScreen()
    
    private static void writeString(FileWriter fw, String str) {
        try {
            fw.write(str + NEWLINE);
        } // end try
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } // end catch

//        System.out.println(str);
    } // end writeString()

    /* =========VisualPlugin========= */
    public JComponent getPluginVisual() {
        // TODO Auto-generated method stub
        return null;
    } // end getPluginVisual()

    public JMenu getPluginMenu() {
        return menu;
    } // end getPluginMenu()
    
    public static void main(String[] args) {
    	getBytes("gnw");
	}
    
    private static byte[] getBytes(String input) {
    	byte[] ba = new byte[]{};
    	Charset charset = Charset.forName("ISO-8859-1");
        CharsetEncoder encoder = charset.newEncoder();
        
        try {
            // Convert a string to ISO-LATIN-1 bytes in a ByteBuffer
            // The new ByteBuffer is ready to be read.
            ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(input));
            ba =  bbuf.array();
            
        } catch (CharacterCodingException e) {
        } 	
        return ba;    	
    }
    
} // end MFGUtil
